package com.ruoyi.system.controller;



import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.ruoyi.common.redis.annotation.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.ServletUtils;
import com.fasterxml.jackson.annotation.JsonView;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.SysFactory;
import com.ruoyi.system.domain.SysFactory.factoryErpView;
import com.ruoyi.system.service.ISysFactoryService;

/**
 * 基地 提供者
 *
 * @author ygx
 * @date 2020-06-13
 */
@RestController
@RequestMapping("sysFactory")
public class SysFactoryController extends BaseController
{

	@Autowired
	private ISysFactoryService sysFactoryService;

	/**
	 * 查询${tableComment}
	 */
	@GetMapping("get/{factoryId}")
	public SysFactory get(@PathVariable("factoryId") Long factoryId)
	{
		return sysFactoryService.selectSysFactoryById(factoryId);

	}

	/**
	 * 查询基地列表
	 */
	@GetMapping("list")
	public R list(SysFactory sysFactory)
	{
		startPage();
        return result(sysFactoryService.selectSysFactoryList(sysFactory));
	}

	/**
     * 查询所有生产基地
     *
     * @return 生产基地列表
     */
	@GetMapping("all")
	public R all() {
		return R.ok().put("rows",sysFactoryService.selectFactoryAll());
	}

	/**
     * 查询所有生产基地
     *
     * @return 生产基地Id列表
     */
	@GetMapping("allId")
	@JsonView(value = SysFactory.factoryIdView.class)
	public R allId() {
		return R.ok().put("rows",sysFactoryService.selectFactoryAll());
	}

	/**
	 * 根据用户查询基地列表
	 */
	@GetMapping("listByUserId/{userId}")
	public R getErpdeptByfactory(@PathVariable(value="userId") Long userId , ModelMap mmp)
	{
        startPage();
        return result(sysFactoryService.selectSysFactoryListByUserid(userId));
	}

    /**
     * 根据基地userid查询工厂 erp采购部门及币种
    */
	@GetMapping("getErpdeptByfactory/{userId}")
	@JsonView(value = SysFactory.factoryUserView.class)
	public R selectSysFactoryByUserId(@PathVariable(value="userId") Long userId , ModelMap mmp)
	{
		return jacResult(sysFactoryService.selectSysFactoryByUserId(userId));
	}

    /**
      * 根据基地code、name、id查询erp部门及币种
	 * 假如增加判断逻辑，@rediscatch需要写到实现层
     */
	@PostMapping("getErpdeptByfactory")
	@JsonView(value = SysFactory.factoryErpView.class)
	@RedisCache(key = "factory_erpdept", fieldKey = "#sysFactory.getFactoryCode()")
	public R listByUserid(@RequestBody SysFactory sysFactory)
	{
		return jacResult(sysFactoryService.selectErpdeptByfactory(sysFactory));
	}

	/**
	 * 手机端获取所有基地下的erp部门及币种
	 */
	@PostMapping("getAllErpdept")
//	@RedisCache(key = "factory_allerpdept", fieldKey = "#")
	public R allFactoryList()
	{
//		List<SysFactory> sysFactories = sysFactoryService.selectErpdeptByfactory(new SysFactory());
//		Iterator<SysFactory> iterator = sysFactories.iterator();
//		while (iterator.hasNext()){
//			iterator.next()
//		}
//		Map<String, List<SysFactory>> map = new HashMap<>();
//		List<Map<String, List<SysFactory>>> collect = sysFactories.stream().map(sf -> {
//			if (!map.containsKey(sf.getFactoryCode())) {
//				ArrayList<SysFactory> newSysFactory = new ArrayList<>();
//				newSysFactory.add(sf);
//				map.put(sf.getFactoryCode(), newSysFactory);
//			} else {
//				List<SysFactory> sysFactory = map.get(sf.getFactoryCode());
//				sysFactory.add(sf);
//				map.put(sf.getFactoryCode(), sysFactory);
//			}
//			return map;
//		}).collect(Collectors.toList());
		Long userId = sysFactoryService.selectRedisUserId();
		List<SysFactory> sysFactoryList = sysFactoryService.selectSysFactoryListByUserid(userId);
		List<Object> list = new ArrayList<>();
		for (SysFactory s : sysFactoryList) {
			Map<String,Object> map = new HashMap<>();
			List<SysFactory> sysFactory = sysFactoryService.selectErpdeptByfactory(s);
			List<Map<String, String>> collect = sysFactory.stream().map(sf -> {
				Map<String, String> childrenMap = new HashMap<>();
				childrenMap.put("label", sf.getErpdeptName());
				childrenMap.put("value", sf.getErpdeptCode());
				childrenMap.put("extra", sf.getCurrencyType());
				return childrenMap;
			}).collect(Collectors.toList());
			map.put("label",s.getFactoryName());
			map.put("value",s.getFactoryCode());
			map.put("extra",s.getFactoryId());
			map.put("children",collect);
			list.add(map);
		}
		return jacResult(list);
	}

    /**
     * 根据userid查询erp部门及币种
    */
	@GetMapping("getErpdeptByUserId")
	@JsonView(value = SysFactory.factoryErpView.class)
	public R getErpdeptByUserId()
	{
		return jacResult(sysFactoryService.selectErpdeptByUserId());
	}


	/**
	 * 根据token查询基地列表
	 */
	@GetMapping("listByToken")
	public R listByToken(ModelMap mmp)
	{
		Long userId = sysFactoryService.selectRedisUserId();
		return R.ok().put("rows",sysFactoryService.selectSysFactoryListByUserid(userId));
	}

	   /**
     * 根据角色编号查询基地编号（用于勾选）
     * @param roleId
     * @return
     * @author zmr
     */
    @GetMapping("role/{roleId}")
    public List<SysFactory> role(@PathVariable("roleId") Long roleId)
    {
        if (null == roleId || roleId <= 0) return null;
        return sysFactoryService.selectFactoryIdsByRoleId(roleId);
    }


    /**
     * 将默认基地插入redis
     */
    @GetMapping("insertRedis")
    public R insertRedisDefault()
    {
      R r = new R();
      String result = "1";
         HttpServletRequest request = ServletUtils.getRequest();
         Long userId = Long.valueOf(request.getHeader(Constants.CURRENT_ID));
      List<SysFactory> factorys = sysFactoryService.selectSysFactoryListByUserid(userId);
      if (factorys.size() == 0 || factorys == null)
      {
        result = sysFactoryService.insertRedis("00000001");
      }
      else {
        result = sysFactoryService.insertRedis(factorys.get(0).getFactoryCode());
    }

      if (!result.equals("基地信息保存成功")) {
        r.put("code", 500);
        r.put("msg", result);
        return r;
      }
        else {
         r.put("code", 0);
       r.put("msg", "success");
        }
      return r;
    }


	/**
	 * 将用户选择的基地插入redis
	 */
	@GetMapping("insertRedis/{factoryCode}")
	public R insertRedis(@PathVariable("factoryCode") String factoryCode)
	{   R r = new R();
	  String result = sysFactoryService.insertRedis(factoryCode);
	  if (!result.equals("基地信息保存成功")) {
	    r.put("code", 500);
	    r.put("msg", result);
	    return r;
	  }
	    else {
	     r.put("code", 0);
	 	 r.put("msg", "success");
	    }
	  return r;
	}

	 /**
     *  从redis获取用户选择的基地(后端其它服务调用)
     *
     * @param 无
     * @return 基地
     */
	@GetMapping("getRedisFactory/{token}")
	   public String getRedisFactory(@PathVariable String token) {
		String result = sysFactoryService.selectRedisFactory(token);
		System.out.println(result);
        return result;
	}

	 /**
     *  从redis获取用户选择的基地(前端调用)
     *
     * @param 无
     * @return 基地
     */
	@GetMapping("getRedisFactoryVue")
	   public R getRedisFactoryVue() {
		HttpServletRequest request = ServletUtils.getRequest() ;
	    String token = request.getHeader("token");
		String result = sysFactoryService.selectRedisFactory(token);
		System.out.println(result);
        return jacResultString("factoryCode",result);
	}

	/**
	 * 新增保存基地
	 */
	@PostMapping("save")
	public R addSave(@RequestBody SysFactory sysFactory)
	{
		return toAjax(sysFactoryService.insertSysFactory(sysFactory));
	}

	/**
	 * 修改保存基地
	 */
	@PostMapping("update")
	public R editSave(@RequestBody SysFactory sysFactory)
	{
		return toAjax(sysFactoryService.updateSysFactory(sysFactory));
	}

	/**
	 * 删除${tableComment}
	 */
	@PostMapping("remove")
	public R remove(String ids)
	{
		return toAjax(sysFactoryService.deleteSysFactoryByIds(ids));
	}

}
